package ajax;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CheckSpeedModel;

import systems.CurrentCheckSpeedProcess;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.gson.Gson;

import entities.CheckSpeed;

public class CheckSpeedProcessAjax extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		int status = 0; //0-process, 1-done
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (name == null || name.isEmpty()) {
			return ;
		}
		
		name = UrlHelper.getMainDomain(name);
		
		if (!UrlHelper.checkDomain(name)) {
			return ;
		}
		
		CheckSpeedModel checkSpeedModel = CheckSpeedModel.getInstance();
		CheckSpeed checkSpeed = checkSpeedModel.get(name);
		ArrayList<String> recent_domains = CurrentCheckSpeedProcess.getDomains();
		
		if (checkSpeed == null && !recent_domains.contains(name)) {
			checkSpeed = new CheckSpeed();
			checkSpeed.setProcessing(true);
			checkSpeed.setDomain(name);
			
			Queue queue = QueueFactory.getDefaultQueue();
			queue.add(TaskOptions.Builder.withUrl("/queue-process-check-speed/" + name).method(Method.GET));
			
			CurrentCheckSpeedProcess.insert(name);
			recent_domains = CurrentCheckSpeedProcess.getDomains();
		}
		
		if (checkSpeed != null && !recent_domains.contains(name) && !checkSpeed.isProcessing()) {
			status = 1;
		}
		
		String json = new Gson().toJson(status);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}
